//
//  MyDownLoadView.m
//  ssssss
//
//  Created by dlios on 14-11-25.
//  Copyright (c) 2014年 age. All rights reserved.
//

#import "MyDownLoadView.h"
#import "WMEMusicDownLoadManager.h"
#import <AVFoundation/AVFoundation.h>

@interface MyDownLoadView ()
@property (nonatomic,retain)NSMutableArray *cacheArray;
@property (nonatomic,retain)NSMutableArray *webArray;
@property (nonatomic,retain)NSString *cachePath;
@property (nonatomic,retain)NSString *webPath;
@property (nonatomic,retain)NSTimer *timer;
@property (nonatomic,assign)NSInteger number;

@property (nonatomic, strong)AVAudioPlayer *player;
@end

@implementation MyDownLoadView

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.title = @"下载管理";
    [self getData];
    if (_webArray.count != 0) {
       _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(getData) userInfo:nil repeats:YES];
    }
    
}

- (void)getData
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    _webPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Temp"];
    _cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Cache"];
    if ([fileManager fileExistsAtPath:_cachePath]) {
        
        NSError *error = nil;
        NSArray *array = [fileManager contentsOfDirectoryAtPath:_cachePath error:&error];
        if (error != nil) {
            NSLog(@"%@",error);
        }
        else
        {
            array = [fileManager subpathsOfDirectoryAtPath:_cachePath error:&error];
            self.cacheArray = [NSMutableArray arrayWithArray:array];
            if (error != nil) {
                NSLog(@"%@",error);
            }
//            else NSLog(@"===%@",self.cacheArray);
        }
    }
    if ([fileManager fileExistsAtPath:_webPath]) {
        
        NSError *error = nil;
        NSArray *array2 = [fileManager contentsOfDirectoryAtPath:_webPath error:&error];
        if (error != nil) {
            NSLog(@"%@",error);
        }
        else
        {
            array2 = [fileManager subpathsOfDirectoryAtPath:_webPath error:&error];
            self.webArray = [NSMutableArray arrayWithArray:array2];
            if (error != nil) {
                NSLog(@"%@",error);
            }
//            else NSLog(@"!!!%@",self.webArray);
        }
    }
    
    NSInteger a = 0;
    NSInteger b = 0;
    if (_cacheArray.count != 0) {
        a = 1;
    }
    if (_webArray.count != 0) {
        b = 1;
    }
    _number = a + b;
    
    if (_number == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"目前没有下载任务!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
    }
    if (_webArray.count == 0) {
        [_timer invalidate];
    }
    [self.tableView reloadData];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (_number == 2) {
        return section == 0 ? @"正在下载" : @"已完成" ;
    }
    if (_number == 1 && _cacheArray.count != 0) {
        return @"已完成";
    }
    if (_number == 1 && _webArray.count != 0) {
        return @"正在下载";
    }
    else
        return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.

    return _number;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.
    
    if (_number == 2) {
        if (section == 0) {
            return self.webArray.count;
        }
        if (section == 1) {
            return self.cacheArray.count;
        }
    }
    if (_number == 1  && _cacheArray.count != 0) {
        return _cacheArray.count;
    }
    if (_number == 1  && _webArray.count != 0) {
        return _webArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_number == 2) {
        if (indexPath.section == 0) {
            static NSString *identifier = @"cell";
            
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            }
            if (_webArray.count != 0) {
                
                WMEMusicDownLoadManager *music = [WMEMusicDownLoadManager sharedManager];
                
                NSString *path = [_webPath stringByAppendingString:[NSString stringWithFormat:@"/%@",_webArray[indexPath.row]]];
                NSFileManager* manager = [NSFileManager defaultManager];
                long long sizes = [[manager attributesOfItemAtPath:path error:nil] fileSize];
                 float vlaue = (float)sizes/(float)music.total;
                cell.detailTextLabel.text = [NSString stringWithFormat:@"已下载: %0.2f %%",vlaue * 100];
            }
           
            cell.textLabel.text = _webArray[indexPath.row];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            return cell;
        }
        if (indexPath.section == 1) {
            static NSString *identifier = @"cell2";
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            }
            cell.textLabel.text = _cacheArray[indexPath.row];
            
            return cell;
        }
    }
    if (_number == 1) {
        
            static NSString *identifier = @"cell3";
            
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            }
        if (_webArray.count != 0) {
            
            WMEMusicDownLoadManager *music = [WMEMusicDownLoadManager sharedManager];
            
            NSString *path = [_webPath stringByAppendingString:[NSString stringWithFormat:@"/%@",_webArray[indexPath.row]]];
            NSFileManager* manager = [NSFileManager defaultManager];
            long long sizes = [[manager attributesOfItemAtPath:path error:nil] fileSize];
            float vlaue = (float)sizes/(float)music.total;
            cell.textLabel.text = _webArray[indexPath.row];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"已下载: %0.2f %%",vlaue *100];
        }

            else cell.textLabel.text = _cacheArray[indexPath.row];

            return cell;
            
        
    }

    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_cacheArray.count) {
//        NSURL *url = [NSURL fileURLWithPath:_cacheArray[indexPath.row]];
        NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", _cachePath, _cacheArray[indexPath.row]]];
//        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//        if (self.player) {
//            [self.player prepareToPlay];
//        }
//        [self.player play];
        [ES_DefaultManager playingWithURL:url];
        
        
    }
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
